<template>
  <a-card :bordered="false">
    <div v-if="modelList.length != 0">
      <div class="model_content">
        <div v-for="(item, index) in modelList" :key="item.modelId" class="model_item" @click="modelClick(item)" :class="{ 'active_modekitem': item.modelId == currentModelId }">
          {{ item.name }}
        </div>
      </div>
    </div>
    <div v-else> <a-empty description="暂无型号" /></div>
    <div class="table-operator">
      <span>
        <a-button type="primary" @click="getDetails">添加物料</a-button>
        <a-button type="primary" @click="edit">编辑</a-button>
        <a-button type="primary" @click="$refs.addModelForm.add(kanbanType)">新增型号</a-button>
        <a-button type="danger" @click="delModel">删除</a-button>
        <a-button type="danger" @click="$refs.dosageTable.init(selectedRowKeys)" :disabled="selectedRowKeys.length == 0" v-if="hasBtnPremission(['emsModel:list'])">月用量表</a-button>
      </span>
    </div>

    <s-table ref="table" :scroll="{ x: 1400, y: 1000 }" size="default" :columns="columnsDynamic" :data="loadData" :alert="true" :rowKey="(record) => record.materialId" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

      <span slot="actionMaterial" slot-scope="text, record">
        <a @click="editAnotherName(record)">编辑别名/排序</a>
        <template>
          <a-divider type="vertical" />
          <span>
            <a-popconfirm placement="topRight" title="确认删除？" @confirm="handleConfirmDel(record)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
        <template>
          <a-divider type="vertical" />
          <span>
            <a @click="$refs.useChart.show({ ...record, typeId: 1 })">出库情况</a>
          </span>
        </template>
      </span>
      <span slot="image" slot-scope="text,record">
        <image-preview1 :images="text" :imageUrl="record.emsMaterialResult.imageUrl" />
      </span>
      <span slot="ScOrderNumber" slot-scope="record">
        <a-button type="link" @click="$refs.orderNumModal.init(record)">详情</a-button>
      </span>
    </s-table>

    <addModelForm ref="addModelForm" @add="handleAddModelForm" @edit="handleEditModelForm" />
    <add-form ref="addForm" @ok="handleAddFormOk"></add-form>
    <a-modal title="编辑别名/排序" :visible="anotherNameVisiable" @ok="handleAnotherNameOk" width="40%" @cancel="handleAnotherNameCancel">
      <a-form :label-col="{ span: 2 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="排序">
          <a-input-number style="width: 100%;" v-model="currentAnotherName.sort" :min="0" />
        </a-form-item>
        <a-form-item label="别名">
          <a-textarea placeholder="别名" :maxlength="200" :auto-size="{ minRows: 5 }" v-model="currentAnotherName.anotherName" />
        </a-form-item>
      </a-form>

    </a-modal>
    <use-chart ref="useChart" />
    <dosageTable ref="dosageTable"></dosageTable>
    <orderNumModal ref="orderNumModal"></orderNumModal>
  </a-card>
</template>

<script>
import { STable } from '@/components'
import moment from 'moment'
// import { del, page } from '@/api/modular/main/emsmaterial/emsMaterialManage'
import useChart from './useChart'

import addModelForm from './addModelForm'
import addForm from './addForm.vue';

import dosageTable from './components/dosageTable.vue';
import orderNumModal from './components/orderNumModal.vue';

import { list, page, modelMaterialEdit, edit, del, deleteModel, outStoreAnalysis } from '@/api/modular/main/emsModel/emsModel'

export default {
  components: {
    STable,
    addModelForm,
    addForm,
    useChart,
    dosageTable,
    orderNumModal
  },
  mounted() {

  },
  data() {
    return {
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      modelList: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        let that = this;
        return page(Object.assign(parameter, that.queryParam)).then((res) => {
          return res.data
        })
      },
      sourceData: [],
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      previewImage: '',
      orgList: [],
      suppliers: [],
      orgs: [],
      viewState: '',
      currentModel: null,
      currentModelId: null,
      anotherNameVisiable: false,//编辑别名弹框
      currentAnotherName: {},
    }
  },
  created() {
    console.log("进入-------this.getModelList()");

    this.getModelList();
  },
  mounted() {
  },
  computed: {
    kanbanType() {
      let viewState = this.routePath.type
      return viewState
    },
    routePath() {
      let urlParam = this.$util.getUrlParam(this.$route.path)
      return urlParam
    },

    columnsDynamic() {
      let result
      result = [
        {
          title: '序号', width: '80px',
          align: 'center',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '类型',
          width: '80px',
          dataIndex: 'emsMaterialResult.materialTypeName'
        },
        {
          title: '排序',
          width: '60px',
          dataIndex: 'sort'
        },
        {
          title: '料号',
          width: '120px',
          dataIndex: 'emsMaterialResult.materialCode'
        },
        {
          title: '物料名称',
          width: '120px',
          dataIndex: 'emsMaterialResult.materialName'
        },
        {
          title: '采购价',
          width: '120px',
          dataIndex: 'emsMaterialResult.purchasePrice',
        },
        {
          title: '别名',
          dataIndex: 'anotherName',
          width: '450px',
          ellipsis: true
        },
        {
          title: '图片',
          dataIndex: 'emsMaterialResult.image',
          width: '120px',
          // customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
          scopedSlots: { customRender: 'image' }
        },
        {
          title: '实时库存',
          width: '120px',
          dataIndex: 'inventoryNumber'
        },
        {
          title: '预计使用库存',
          width: '120px',
          dataIndex: 'expectUseInventoryNumber'
        },
        {
          title: '预采购数量',
          width: '120px',
          dataIndex: 'expectPurchaseNumber'
        },
        {
          title: '剩余库存',
          width: '100px',
          dataIndex: 'remainingInventoryNumber'
        },
        {
          title: '生产单',
          width: '100px',
          // dataIndex: 'expectUseInventoryScOrderNumber'
          scopedSlots: { customRender: 'ScOrderNumber' }
        },
        {
          title: '操作',
          width: '180px',
          dataIndex: 'actionMaterial',
          fixed: 'right',
          align: 'center',
          scopedSlots: { customRender: 'actionMaterial' }
        }
      ]
      return result
    },
  },
  watch: {
    routePath() {
      this.selectedRowKeys = []
      this.selectedRows = []
      console.log("进入watch");
      this.$refs.table.clearSelected();
      this.getModelList();

    }
  },
  methods: {
    /**
     * 型号点击
     * @param item 
     */
    modelClick(item) {
      this.currentModelId = item.modelId;
      this.currentModel = item;
      this.queryParam.modelId = this.currentModelId;
      this.queryParam.type = this.kanbanType;
      setTimeout(() => {
        this.$refs.table.refresh();
      }, 200);
    },
    getDetails() {
      if (this.currentModelId == -1) {
        this.$message.error("暂无型号");
        return
      }
      page({
        modelId: this.currentModelId
      }).then(res => {
        this.sourceData = res.data.rows;
        this.$refs.addForm.init('', this.sourceData)
      })
    },
    edit() {
      if (this.currentModelId == -1) {
        this.$message.error("暂无型号");
        return
      }
      this.$refs.addModelForm.edit(this.currentModel, this.kanbanType)
    },
    /**
     * 添加物料
     * @param data 
     */
    handleAddFormOk(data) {
      let emsModelMaterialList = data.selectedRows.map(item => {
        return {
          materialId: item.materialId,
          anotherName: item.anotherName,
          sort: item.sort,
        }
      })

      let param = {
        type: this.kanbanType,
        status: 0,
        modelId: this.currentModelId,
        emsModelMaterialList: emsModelMaterialList
      }
      edit(param).then(res => {
        this.getModelList('edit');
        this.$message.success("添加成功");
      })
    },
    /**
     * 编辑别名
     * @param record 
     */
    editAnotherName(record) {
      this.anotherNameVisiable = true;
      this.currentAnotherName = record;
    },
    /**
     * 删除物料
     * @param record 
     */
    handleConfirmDel(record) {
      del({
        modelMaterialId: record.modelMaterialId
      }).then(res => {
        if (res.code == 200) {
          this.getModelList();
          this.$message.success("删除成功");
        }
      })
    },
    handleAnotherNameOk() {
      modelMaterialEdit(this.currentAnotherName).then(res => {
        this.getModelList('edit');
        this.$message.success("修改成功");
        this.anotherNameVisiable = false;
      })
    },
    handleAnotherNameCancel() {
      this.anotherNameVisiable = false;
    },
    //获取型号列表
    getModelList(searchType = '') {
      let that = this;
      let type = that.kanbanType;
      list({
        type: type
      }).then(res => {
        console.log(res);
        that.modelList = res.data;
        if (that.modelList.length != 0) {
          if (searchType == 'add') {
            // that.currentModelId = res.data;
            // that.currentModel = that.modelList[that.modelList.length - 1];
          } else if (searchType == 'edit') {
            that.currentModelId = that.currentModel.modelId;
            // that.currentModel = that.currentModel;
          } else {
            that.currentModelId = that.modelList[0].modelId;
            that.currentModel = that.modelList[0];
          }
        } else {
          that.currentModelId = -1;
          that.currentModel = {};
        }

        this.queryParam.modelId = that.currentModelId
        this.queryParam.type = type
        setTimeout(() => {
          that.$refs.table.refresh();
        }, 200);
      })
    },
    //新增
    handleAddModelForm(data) {
      this.getModelList('add');
      this.currentModelId = data;
    },
    //编辑
    handleEditModelForm() {
      this.getModelList('edit');
    },
    /**
     * 删除型号	
     */
    delModel() {
      if (this.currentModelId == -1) {
        this.$message.error("暂无型号");
        return
      }
      let that = this;
      this.$confirm({
        content: '确定删除当前型号吗？',
        centered: true,
        onOk() {
          deleteModel({
            modelId: that.currentModelId
          }).then((res) => {
            if (res.code == 200) {
              that.getModelList();
              that.$message.success("删除成功");
            }
            return false
          });
        },
        cancelText: '取消',
        onCancel() {
          return new Promise(resolve => {
            return resolve(false)
          })
        },
      });
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
  },
}
</script>

<style lang="less">
.model_content {
	display: flex;
	align-items: center;
	flex-wrap: wrap;

	.model_item {
		border: 1px solid #ccc;
		border-radius: 5px;
		padding: 4px 15px;
		margin: 10px;
		cursor: pointer;
		font-size: 14px;
	}
}

.active_modekitem {
	background-color: #409EFF;
	color: #fff;
}

.table-operator {
	margin: 18px 10px;
}
</style>
